<template>
  <section 
    id="cases" 
    class="p-24 bg-white"
  >
    <div class="container mx-auto px-4 sm:px-6 lg:px-8">
      <!-- 标题区域 - 使用固定中文 -->
      <div class="text-center max-w-3xl mx-auto mb-16">
        <span :style="{ color: primaryColor }" class="font-medium">成功案例</span>
        <h2 class="text-[clamp(2rem,5vw,2.5rem)] font-bold mt-2 mb-4 text-gray-800">我们的客户故事</h2>
        <p class="text-lg text-gray-600 leading-relaxed">探索我们如何帮助各行各业的客户解决挑战，实现业务增长</p>
      </div>
      
      <!-- 案例筛选 -->
      <div class="flex flex-wrap justify-center gap-4 mb-12">
        <button 
          @click="filterByCategory('all')"
          class="px-5 py-2 rounded-full text-sm cursor-pointer transition-all duration-300"
          :style="activeCategory === 'all' ? activeFilterStyle : inactiveFilterStyle"
        >
          全部案例
        </button>
        <button 
          v-for="category in categories" 
          :key="category.value"
          @click="filterByCategory(category.value)"
          class="px-5 py-2 rounded-full text-sm cursor-pointer transition-all duration-300"
          :style="activeCategory === category.value ? activeFilterStyle : inactiveFilterStyle"
        >
          {{ category.label }}
        </button>
      </div>
      
      <!-- 加载状态 -->
      <div v-if="isLoading" class="flex flex-col items-center justify-center py-20">
        <div class="w-16 h-16 border-4 border-gray-200 border-t-primary rounded-full animate-spin"></div>
        <p class="mt-4 text-gray-600">正在加载案例数据...</p>
      </div>
      
      <!-- 案例展示 -->
      <div v-else :class="gridClass">
        <!-- 显示案例列表 -->
        <div 
          v-for="(caseItem, index) in filteredCases" 
          :key="index" 
          class="bg-gray-50 rounded-xl overflow-hidden transition-all duration-300 hover:translate-y-[-5px] hover:shadow-xl cursor-pointer"
          :style="cardStyle"
          @click="handleCaseClick(caseItem)"
        >
          <div class="relative">
            <img 
              :src="caseItem.image" 
              :alt="caseItem.title" 
              class="w-full h-60 object-cover"
              :class="{ 'grayscale': caseItem.grayscale }"
            >
            <div :style="{ backgroundColor: primaryColor }" class="absolute top-4 left-4 text-white text-sm px-3 py-1 rounded-full opacity-90">
              {{ getCategoryLabel(caseItem.category) }}
            </div>
          </div>
          <div class="p-6">
            <h3 class="text-xl font-bold mb-2">{{ caseItem.title }}</h3>
            <p class="text-dark/70 mb-4">{{ caseItem.description }}</p>
            <a 
              href="#" 
              :style="{ color: primaryColor }" 
              class="font-medium inline-flex items-center hover:underline"
              @click.stop="handleDetailClick(caseItem, $event)"
            >
              查看详情
              <i class="fa fa-arrow-right ml-2"></i>
            </a>
          </div>
        </div>
        
        <!-- 空状态显示 -->
        <div v-if="filteredCases.length === 0" class="col-span-full flex flex-col items-center justify-center py-20 text-center">
          <i class="fa fa-folder-open text-6xl text-gray-300 mb-4"></i>
          <h3 class="text-xl font-semibold text-gray-700 mb-2">暂无案例数据</h3>
          <p class="text-gray-500 max-w-md">
            {{ activeCategory === 'all' ? '当前没有可展示的案例' : '该分类下暂无案例数据' }}
          </p>
          <button 
          v-if="dataSourceUrl" 
          @click="refresh" 
          class="mt-6 px-4 py-2 border border-primary text-primary rounded-lg hover:bg-primary/5 transition-all"
        >
          刷新数据
        </button>
        </div>
      </div>
      
      <!-- 查看更多按钮 -->
      <div class="text-center mt-12" v-if="showLoadMore && hasMoreCases">
        <button 
          @click="handleLoadMore"
          class="inline-flex items-center px-6 py-3 border border-primary text-primary rounded-lg hover:bg-primary/5 transition-all duration-300"
          :disabled="isLoadingMore"
        >
          <span v-if="!isLoadingMore">查看更多案例</span>
          <span v-if="isLoadingMore">加载中...</span>
          <i class="fa fa-long-arrow-right ml-2"></i>
        </button>
      </div>
    </div>
  </section>
</template>

<script>
export default {
  name: 'CustomerCases',
  // 低代码平台元数据 - 移除语言相关配置
  lowcode: {
    meta: {
      name: 'customer-cases',
      displayName: '客户案例',
      description: '展示公司成功案例和客户故事的组件',
      icon: 'fa-folder-open',
      category: '内容展示',
      version: '1.0.0',
      isContainer: false
    },
    
    configPanel: [
      {        title: '基本配置',        fields: [          {            name: 'primaryColor',            label: '主题色',            type: 'color',            defaultValue: '#165DFF'          },          {            name: 'showLoadMore',            label: '显示加载更多',            type: 'boolean',            defaultValue: true          },          {            name: 'itemsPerPage',            label: '每页显示数量',            type: 'number',            min: 1,            max: 20,            defaultValue: 6          },          {            name: 'dataSourceUrl',            label: '数据源URL',            type: 'text',            defaultValue: '',            description: 'API接口地址，用于动态加载案例数据'          },          {            name: 'autoLoad',            label: '自动加载数据',            type: 'boolean',            defaultValue: true          }        ]      },
      {
        title: '布局配置',
        fields: [
          {
            name: 'columnLayout',
            label: '列布局',
            type: 'select',
            options: [
              { label: '1列', value: '1' },
              { label: '2列', value: '2' },
              { label: '3列', value: '3' },
              { label: '自动适应', value: 'auto' }
            ],
            defaultValue: 'auto'
          },
          {
            name: 'cardRadius',
            label: '卡片圆角',
            type: 'number',
            min: 0,
            max: 20,
            defaultValue: 8
          },
          {
            name: 'cardShadow',
            label: '卡片阴影',
            type: 'switch',
            defaultValue: true
          }
        ]
      }
    ],
    
    events: [
      {
        name: 'caseClick',
        label: '案例卡片点击',
        description: '点击案例卡片时触发',
        parameters: [
          { name: 'case', type: 'object', description: '案例信息对象' }
        ]
      },
      {
        name: 'detailClick',
        label: '查看详情点击',
        description: '点击查看详情链接时触发',
        parameters: [
          { name: 'case', type: 'object', description: '案例信息对象' }
        ]
      },
      {
        name: 'loadMore',
        label: '加载更多',
        description: '点击加载更多按钮时触发'
      },
      {
        name: 'categoryChange',
        label: '分类切换',
        description: '切换分类筛选时触发',
        parameters: [
          { name: 'category', type: 'string', description: '选中的分类值' }
        ]
      },
      {
        name: 'dataLoaded',
        label: '数据加载完成',
        description: '从数据源加载数据完成时触发',
        parameters: [
          { name: 'data', type: 'array', description: '加载的案例数据' }
        ]
      },
      {
        name: 'dataLoadError',
        label: '数据加载失败',
        description: '从数据源加载数据失败时触发',
        parameters: [
          { name: 'error', type: 'object', description: '错误信息' }
        ]
      }
    ],
    
    actions: [
      {
        name: 'filterByCategory',
        label: '按分类筛选',
        description: '按分类筛选案例',
        parameters: [
          { name: 'category', type: 'string', required: true, description: '分类值' }
        ]
      },
      {
        name: 'refresh',
        label: '刷新案例',
        description: '重新加载案例数据'
      }
    ]
  },
  
  props: {
      primaryColor: {
        type: String,
        default: '#165DFF'
      },
      showLoadMore: {
        type: Boolean,
        default: true
      },
      itemsPerPage: {
        type: Number,
        default: 6,
        validator: (value) => value > 0 && value <= 20
      },
      dataSourceUrl: {
        type: String,
        default: ''
      },
      autoLoad: {
        type: Boolean,
        default: true
      },
    columnLayout: {
      type: String,
      default: 'auto',
      validator: (value) => ['1', '2', '3', 'auto'].includes(value)
    },
    cardRadius: {
      type: Number,
      default: 8
    },
    cardShadow: {
      type: Boolean,
      default: true
    },
    children: {
      type: Array,
      default: () => []
    },
    categories: {
      type: Array,
      default: () => [
        { label: '金融行业', value: 'finance' },
        { label: '制造业', value: 'manufacturing' },
        { label: '零售业', value: 'retail' },
        { label: '医疗健康', value: 'healthcare' },
        { label: '教育培训', value: 'education' },
        { label: '物流行业', value: 'logistics' }
      ]
    },
    cases: {
      type: Array,
      default: () => [
        {
          id: 1,
          title: '某大型银行数字化转型',
          description: '帮助银行实现全渠道数字化服务，提升客户体验，业务处理效率提升40%。',
          image: 'https://picsum.photos/seed/case1/600/400',
          category: 'finance',
          url: '#',
          grayscale: false
        },
        {
          id: 2,
          title: '智能制造企业生产管理系统',
          description: '为制造企业构建智能生产管理平台，生产效率提升35%，成本降低20%。',
          image: 'https://picsum.photos/seed/case2/600/400',
          category: 'manufacturing',
          url: '#',
          grayscale: false
        },
        {
          id: 3,
          title: '连锁零售企业全渠道转型',
          description: '构建线上线下一体化零售平台，客户转化率提升28%，销售额增长32%。',
          image: 'https://picsum.photos/seed/case3/600/400',
          category: 'retail',
          url: '#',
          grayscale: false
        },
        {
          id: 4,
          title: '医疗集团信息化建设',
          description: '为医疗集团构建一体化信息平台，患者满意度提升45%，运营效率提升30%。',
          image: 'https://picsum.photos/seed/case4/600/400',
          category: 'healthcare',
          url: '#',
          grayscale: false
        },
        {
          id: 5,
          title: '教育机构在线学习平台',
          description: '打造智能化在线教育平台，用户规模增长150%，学习效果提升显著。',
          image: 'https://picsum.photos/seed/case5/600/400',
          category: 'education',
          url: '#',
          grayscale: false
        },
        {
          id: 6,
          title: '物流企业智能调度系统',
          description: '构建智能物流调度平台，配送效率提升38%，运营成本降低25%。',
          image: 'https://picsum.photos/seed/case6/600/400',
          category: 'logistics',
          url: '#',
          grayscale: false
        }
      ]
    }
  },
  
  data() {
    return {
      activeCategory: 'all',
      currentPage: 1,
      isLoadingMore: false,
      isLoading: false,
      originalCases: [],
      // 内部案例数据副本，避免直接修改props
      localCases: []
    };
  },
  
  mounted() {
    // 保存原始案例数据
    this.originalCases = [...this.cases];
    // 初始化本地数据副本
    this.localCases = [...this.cases];
    
    // 如果设置了自动加载且有数据源URL，加载数据
    if (this.autoLoad && this.dataSourceUrl) {
      this.loadDataFromSource();
    }
  },
  
  watch: {
    // 当案例数据变化时重置分页并同步本地数据
    cases: {
      handler(newVal) {
        this.currentPage = 1;
        this.localCases = [...newVal];
      },
      deep: true,
      immediate: true
    },
    
    // 当数据源URL变化时，重新加载数据
    dataSourceUrl: {
      handler(newUrl, oldUrl) {
        if (this.autoLoad && newUrl && newUrl !== oldUrl) {
          this.loadDataFromSource();
        }
      }
    }
  },
  
  computed: {
    // 筛选后的案例
    filteredCases() {
      let result = this.localCases;
      
      // 按分类筛选
      if (this.activeCategory !== 'all') {
        result = result.filter(item => item.category === this.activeCategory);
      }
      
      // 分页处理
      return result.slice(0, this.currentPage * this.itemsPerPage);
    },
    
    // 是否还有更多案例可加载
    hasMoreCases() {
      const filteredTotal = this.activeCategory === 'all' 
        ? this.localCases.length 
        : this.localCases.filter(item => item.category === this.activeCategory).length;
      
      return this.filteredCases.length < filteredTotal;
    },
    
    // 网格布局类名
    gridClass() {
      switch (this.columnLayout) {
        case '1':
          return 'grid grid-cols-1 gap-8';
        case '2':
          return 'grid grid-cols-1 md:grid-cols-2 gap-8';
        case '3':
          return 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8';
        default: // auto
          return 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8';
      }
    },
    
    // 激活的筛选按钮样式
    activeFilterStyle() {
      return {
        backgroundColor: this.primaryColor,
        color: 'white'
      };
    },
    
    // 未激活的筛选按钮样式
    inactiveFilterStyle() {
      return {
        backgroundColor: '#f9fafb',
        color: 'rgba(31, 41, 55, 0.7)'
      };
    },
    
    // 卡片样式
    cardStyle() {
      return {
        borderRadius: `${this.cardRadius}px`,
        boxShadow: this.cardShadow ? '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)' : 'none'
      };
    }
  },
  
  methods: {
    /**
     * 按分类筛选案例
     */
    filterByCategory(category) {
      this.activeCategory = category;
      this.currentPage = 1;
      this.$emit('categoryChange', category);
    },
    
    /**
     * 获取分类的显示标签
     */
    getCategoryLabel(categoryValue) {
      const category = this.categories.find(c => c.value === categoryValue);
      return category ? category.label : categoryValue;
    },
    
    /**
     * 案例卡片点击事件
     */
    handleCaseClick(caseItem) {
      this.$emit('caseClick', caseItem);
    },
    
    /**
     * 查看详情点击事件
     */
    handleDetailClick(caseItem, e) {
      e.stopPropagation();
      this.$emit('detailClick', caseItem);
      
      // 如果配置了链接且不是#，可以自动跳转
      if (caseItem.url && caseItem.url !== '#') {
        window.open(caseItem.url, '_blank');
      }
    },
    
    /**
     * 加载更多案例
     */
    async handleLoadMore() {
      this.isLoadingMore = true;
      this.$emit('loadMore');
      
      // 模拟加载延迟
      try {
        await new Promise(resolve => setTimeout(resolve, 1000));
        this.currentPage++;
      } finally {
        this.isLoadingMore = false;
      }
    },
    
    /**
     * 从API数据源加载数据
     */
    async loadDataFromSource() {
      if (!this.dataSourceUrl) {
        console.warn('数据源URL为空，无法加载数据');
        return;
      }
      
      this.isLoading = true;
      
      try {
        // 发送请求获取数据
        const response = await fetch(this.dataSourceUrl);
        
        if (!response.ok) {
          throw new Error(`HTTP错误! 状态码: ${response.status}`);
        }
        
        const data = await response.json();
        
        // 验证数据格式
        let validData;
        if (Array.isArray(data)) {
          validData = data;
        } else if (data.cases && Array.isArray(data.cases)) {
          validData = data.cases;
        } else {
          throw new Error('数据格式不正确，需要包含案例数组');
        }
        
        // 更新本地数据副本
        this.localCases = [...validData];
        this.originalCases = [...validData];
        
        // 通知父组件更新props
        this.$emit('update:cases', [...validData]);
        this.$emit('dataLoaded', validData);
      } catch (error) {
        console.error('从数据源加载数据失败:', error);
        this.$emit('dataLoadError', error);
      } finally {
        this.isLoading = false;
      }
    },
    
    /**
     * 刷新案例数据
     */
    refresh() {
      this.currentPage = 1;
      
      // 从API数据源加载数据
      if (this.dataSourceUrl) {
        this.loadDataFromSource();
      } else {
        // 重置为原始数据
        this.localCases = [...this.originalCases];
        this.$emit('update:cases', [...this.originalCases]);
      }
    }
  }
};
</script>
